package controllers;

import is.ru.honn.rupin.data.UserDataGateway;
import is.ru.honn.rupin.domain.User;
import is.ru.honn.rupin.domain.UserAuthentication;
import is.ru.honn.rupin.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import play.*;
import play.mvc.*;
import play.data.*;
import views.html.index;
import views.html.session.*;
import views.html.signup.summary;

/**
 * Controls login and logout and validation of users
 * @author Einar Sigurðsson
 * @version 1.0, 11/18/12
 */
public class Session extends RuPinController {

    /**
     * login page
     * @return login form
     */
    public static Result login(){
        return ok(
                loginform.render(form(UserAuthentication.class))
        );
    }

    /**
     * clears the current session
     * @return login page
     */
    public static Result logout(){
        session().clear();
        flash("success", "You've been logged out");
        return redirect(
                routes.Session.login()
        );
    }

    /**
     * checks whether there is an active session
     * @return whether a user is logged in
     */
    public static boolean isValidated(){
        return session().get("username") != null;
    }

    /**
     * logs in a user by creating session variables
     * @return index page
     */
    public static Result authenticate(){
        Form<UserAuthentication>  loginForm = form(UserAuthentication.class).bindFromRequest();
        if(loginForm.hasErrors()){
            return badRequest(loginform.render(loginForm));
        } else {
            User user = userService.login(loginForm.get().getUsername(), loginForm.get().getPassword());
            if(user == null)
                return redirect(routes.Session.login());
            else{
                session("username", user.getUsername());
                session("Name", user.getName());
                return redirect(routes.Application.index());
            }



        }
    }
}
